package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.ServerResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    private static final List<String> uriWhiteList = Arrays.asList(
            "/employee/login",
            "/employee/logout",
            "/backend/**",
            "/front/**",
            "/user/sendMsg",
            "/user/login");
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        log.info("record a request, URI:{}", requestURI);
        boolean inWhiteList = uriWhiteList.stream().anyMatch(uri -> PATH_MATCHER.match(uri, requestURI));
        if (inWhiteList) {
            filterChain.doFilter(request, response);
            return;
        }

        Long employeeId = (Long) request.getSession().getAttribute("employee");
        if (employeeId != null) {
            BaseContext.setId(employeeId);
            filterChain.doFilter(request, response);
            return;
        }

        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {
            BaseContext.setId(userId);
            filterChain.doFilter(request, response);
            return;
        }
        log.info("NOT LOGIN");
        response.getWriter().write(JSON.toJSONString(ServerResultVO.error("NOTLOGIN")));
    }
}
